package com.sws.web.controller.ry_rongyue.wx;

import java.util.List;

import com.sws.weixin.mapper.Template2Mapper;
import com.sws.weixin.service.TemplateService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sws.common.annotation.Log;
import com.sws.common.core.controller.BaseController;
import com.sws.common.core.domain.AjaxResult;
import com.sws.common.enums.BusinessType;
import com.sws.wxtemplate.domain.WechatTemplate;
import com.sws.wxtemplate.service.IWechatTemplateService;
import com.sws.common.utils.poi.ExcelUtil;
import com.sws.common.core.page.TableDataInfo;

/**
 * 微信消息模板Controller
 * 
 * @author dhw
 * @date 2025-06-25
 */
@RestController
@RequestMapping("/ry/template/message")
@Slf4j
public class WechatTemplateController extends BaseController
{
    @Autowired
    private IWechatTemplateService wechatTemplateService;

    @Autowired
    private TemplateService templateService;
    
    @Autowired
    private Template2Mapper template2Mapper;

    /**
     * 查询微信消息模板列表
     */
    @PreAuthorize("@ss.hasPermi('ry/template:message:list')")
    @GetMapping("/list")
    public TableDataInfo list(WechatTemplate wechatTemplate)
    {
        log.info("查询微信消息模板列表");
        startPage();
        List<WechatTemplate> list = wechatTemplateService.selectWechatTemplateList(wechatTemplate);
        return getDataTable(list);
    }

    /**
     * 导出微信消息模板列表
     */
    @PreAuthorize("@ss.hasPermi('ry/template:message:export')")
    @Log(title = "微信消息模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WechatTemplate wechatTemplate)
    {
        List<WechatTemplate> list = wechatTemplateService.selectWechatTemplateList(wechatTemplate);
        ExcelUtil<WechatTemplate> util = new ExcelUtil<WechatTemplate>(WechatTemplate.class);
        util.exportExcel(response, list, "微信消息模板数据");
    }

    /**
     * 获取微信消息模板详细信息
     */
    @PreAuthorize("@ss.hasPermi('ry/template:message:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(wechatTemplateService.selectWechatTemplateById(id));
    }

    /**
     * 新增微信消息模板
     */
    @PreAuthorize("@ss.hasPermi('ry/template:message:add')")
    @Log(title = "微信消息模板", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WechatTemplate wechatTemplate)
    {
        return toAjax(wechatTemplateService.insertWechatTemplate(wechatTemplate));
    }

    /**
     * 修改微信消息模板
     */
    @PreAuthorize("@ss.hasPermi('ry/template:message:edit')")
    @Log(title = "微信消息模板", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WechatTemplate wechatTemplate)
    {
        return toAjax(wechatTemplateService.updateWechatTemplate(wechatTemplate));
    }

    /**
     * 删除微信消息模板
     */
    @PreAuthorize("@ss.hasPermi('ry/template:message:remove')")
    @Log(title = "微信消息模板", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        try {
            // 同步删除 ry_wx_template 表中对应的记录
            for (Long id : ids) {
                WechatTemplate template = wechatTemplateService.selectWechatTemplateById(id);
                if (template != null && template.getTemplateId() != null) {
                    // 根据模板ID删除 ry_wx_template 表中的记录
                    template2Mapper.deleteByTemplateId(template.getTemplateId());
                    log.info("已删除 ry_wx_template 表中的模板，模板ID：{}", template.getTemplateId());
                }
            }
            // 删除 ry_wechat_template 表中的记录
            return toAjax(wechatTemplateService.deleteWechatTemplateByIds(ids));
        } catch (Exception e) {
            log.error("删除模板时发生错误", e);
            return AjaxResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 同步微信消息模板
     */
    @PreAuthorize("@ss.hasPermi('ry/template:message:sync')")
    @Log(title = "同步微信消息模板", businessType = BusinessType.OTHER)
    @GetMapping("/syncTemplates")
    public AjaxResult syncTemplates()
    {
        try {
            log.info("开始同步微信消息模板");
            templateService.fetchAndSaveTemplates();
            return AjaxResult.success("同步成功");
        } catch (Exception e) {
            log.error("同步模板时发生错误", e);
            return AjaxResult.error("同步失败：" + e.getMessage());
        }
    }
}
